<?php
namespace app\admin\controller;

use think\facade\View;
use app\admin\controller\AdminBase;
// use app\common\model\mysql\MallAdminUser;
use app\admin\business\AdminUserService;

class Login extends AdminBase{
	public function initialize(){
		if($this->isLogin()){ //如果已登录，就跳转到后台首页
			// return $this->redirect(url("index/index"));
			redirect('index/index')->send();
		}
	}

	public function index(){
		return View::fetch();
	}

	//登录处理
	public function check(){
		if(!$this->request->isPost()){
			return show(config('status.error'),"请求方式错误");
		}
		// 参数校验
		$username = $this->request->param("username","trim");
		$password = $this->request->param("password","trim");
		$captcha = $this->request->param("captcha","trim");
		/*
		if(empty($username) || empty($password) || empty($captcha)){
			return show(config('status.error'),"参数不能为空");
		}
		*/
		$data = [
			'username' => $username,
			'password' => $password,
			'captcha' => $captcha,
		];

		//validate校验
		$validate = new \app\admin\validate\AdminUser();
		if(!$validate->check($data)){
			return show(config('status.error'),$validate->getError());
		}

		//$adminUserObj = new \app\admin\business\AdminUserService();
		//调用业务逻辑层登录    
		$objAdminUser = new AdminUserService();
		$result = $objAdminUser->login($data);
		
		if($result){
			return show(config('status.success'),"登录ok");
		}
		return show(config('status.error'),"登录失败");

		/*
		// 实例化用户model对象
		$objAdminUser = new MallAdminUser();
		$adminUser = $objAdminUser->getAdminUserByUsername($username);

		if(empty($adminUser) || $adminUser->status != config('status.mysql.normal')){
			
			return show(config('status.error'),"不存在该用户");
		}
		$adminUser = $adminUser->toArray();
		
		// 判断密码是否正确
		if($adminUser['password'] != md5($password)){
			return show(config('status.error'),"用户密码错误");
		}
		
		$data = [
			'update_time' => time(),
			'last_login_time' => time(),
			'last_login_ip' => $this->request->ip(),
		];
		$res = $objAdminUser->updateAdminUserByUserId($adminUser['id'],$data);
		if(empty($res)){
			return show(config('status.error'),"更新失败");
		}
		// 记录session
		session(config('admin.session_admin'),$adminUser);

		return show(config('status.success'),"登录ok");
		*/
	}

	public function md5(){
		// halt(session(config('admin.session_admin')));
		halt(session(config('admin.session_admin')));
		// echo md5('fresh1204');

	}
} 